package com.lnj.orders.controller;


import com.lnj.orders.service.OrdersService;
import com.lnj.orders.utils.AliPayUtil;
import com.lnj.orders.utils.JsonUtil;
import com.lnj.orders.utils.PayOrderRequest;
import com.lnj.orders.utils.ProductOrderInfo;
import com.lnj.utils.OrderMessage;
import com.lnj.utils.RedisKeys;
import com.lnj.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.lnj.utils.RedisKeys.ORDER_PAY_QRCODE;


@Controller
@RequestMapping("/orders/alipay")
public class AliPayController {
    @Autowired
    private AliPayUtil aliPayUtil;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private JsonUtil jsonUtil;

    //    当我们支付完成之后跳转这个请求并携带参数，我们将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @GetMapping("/getPayStatus")
    public ResponseEntity<ResponseResult> getPayStatus(@RequestHeader("X-User-ID") Long userId,@RequestParam("orderId") Long orderId)  {
        Boolean query = aliPayUtil.queryPayStatus(orderId+"");
        if (query){
            //更新订单状态
            ordersService.updateStatus(orderId, 2);
            //删除订单的支付二维码
            stringRedisTemplate.delete(ORDER_PAY_QRCODE + orderId);

            //添加订单的支付记录
            stringRedisTemplate.opsForList().leftPush(RedisKeys.USER_PURCHASES + userId, orderId.toString());

            //获取订单的商品列表
            List<ProductOrderInfo> orderdetalById = ordersService.getOrderdetalById(orderId);
            for (ProductOrderInfo productOrderInfo : orderdetalById) {
                //添加订单的商品被哪些用户浏览的ID
                stringRedisTemplate.opsForSet().add(RedisKeys.PRODUCT_PAY + productOrderInfo.getProductId() + "", userId.toString());
                //删除订单的商品被购买的用户ID
                stringRedisTemplate.opsForSet().remove(RedisKeys.PRODUCT_CART + productOrderInfo.getProductId() + "", userId.toString());
            }
            //设置过期时间
            stringRedisTemplate.expire(RedisKeys.USER_PURCHASES + userId, 30, TimeUnit.DAYS);
            OrderMessage paid = new OrderMessage(orderId, LocalDateTime.now(), "paid", 0, 2);

            //发送支付成功到kafka
            kafkaTemplate.send("orders.paid", jsonUtil.toJson(paid));
            return ResponseEntity.ok(ResponseResult.ok().setData(1));
        }
        return ResponseEntity.ok(ResponseResult.ok().setData(0));
    }


    //获取支付二维码
    @GetMapping("/getPayQRCode")
    public ResponseEntity<ResponseResult> getPayQRCode(@RequestParam("orderId") Long orderId) {
        try {
            String redisKey = ORDER_PAY_QRCODE + orderId;
            // 首先判断是否生成过这个订单的支付二维码
            Boolean hasKey = stringRedisTemplate.hasKey(redisKey);
            if (hasKey != null && hasKey) {
                // 如果生成过，从Redis中查询二维码
                String qrCode =  stringRedisTemplate.opsForValue().get(redisKey);
                // 再次确认值不为null（防止极短时间内过期）
                if (qrCode != null) {
                    return new ResponseEntity<>(ResponseResult.ok("支付二维码获取成功").setData(qrCode), HttpStatus.OK);
                }
            }

            // 如果没有生成过，生成新的支付二维码
            // 根据订单ID查询订单金额
            Double totalPrice = ordersService.calculateTotalPrice(orderId);
            String alipayQRCode = aliPayUtil.generateQRCodePay(orderId+"", totalPrice.toString());

            // 将新生成的二维码存入Redis，设置过期时间（例如5分钟）
            stringRedisTemplate.opsForValue().set(redisKey, alipayQRCode, 30, TimeUnit.MINUTES);

            return new ResponseEntity<>(ResponseResult.ok("支付二维码获取成功").setData(alipayQRCode), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("支付二维码获取失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}